package com.lei.collection.interabale;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @Author LeiXiaoLei
 * @Date 2022/5/9 11:14
 * @Version 1.0
 */
public class RandomStringGenerator<T> implements Iterable<T> {
    private List<T> list;
    private Long recyclingNumber;
    private long count;
    private boolean hasNext = true;

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public RandomStringGenerator() {
    }

    public RandomStringGenerator(List<T> list) {
        this.list = list;
    }

    public RandomStringGenerator(List<T> list, Long recyclingNumber) {
        this.list = list;
        this.recyclingNumber = recyclingNumber;
    }

    /**
     * always run
     *
     * @return T
     */
    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            @Override
            public boolean hasNext() {
                return hasNext;
            }

            @Override
            public T next() {
                if (!Objects.isNull(recyclingNumber)) {
                    count++;
                    if (recyclingNumber.equals(count)) {
                        hasNext = false;
                    }
                }
                return list.get((int) (list.size() * Math.random()));
            }
        };
    }

    public static void main(String[] args) {
        var list = List.of("java","c","c++","python");
        RandomStringGenerator<String> randomStringGenerator = new RandomStringGenerator<>(list,10L);
        randomStringGenerator.forEach(System.out::println);
    }
}
